package main

import (
	"fmt"
	"github.com/boltdb/bolt"
	"whoscored/util/boltdb"

	"strings"
	"strconv"
	"encoding/json"
	"whoscored/util/mysql"
)


func main()  {
	i:=0

	s:=",252-2,108-5,206-4,81-3,74-22,177-21,155-13,182-77,31-95,233-85,225-17,252-7,11-68,45-162,165-41,212-40,81-6,250-12,250-30,247-36,"
	sql:="insert into `match` values "

	boltdb.ScanTx("matchs-2017", func(tx *bolt.Tx) {

		tx.ForEach(func(name []byte, b *bolt.Bucket) error {

			b.ForEach(func(k, v []byte) error {
				//fmt.Println(string(v))

				m:=make(map[string]interface{},0)

				json.Unmarshal(v,&m)
				s1:=m["region"].([]interface{})
				ss:=strconv.FormatFloat(s1[4].(float64), 'f', -1, 64)
				region:=","+s1[1].(string)+"-"+ss+","
				match:=m["match"].([]interface{})

				regionName:=s1[3].(string)
				regionCode:=s1[2].(string)
				tournamentName:=s1[7].(string)
				season:=s1[12].(string)
				stageId:=strconv.FormatFloat(match[0].(float64), 'f', -1, 64)
				matchId:=strconv.FormatFloat(match[1].(float64), 'f', -1, 64)
				timeString:=string(name[0:4])+"-"+string(name[4:6])+"-"+string(name[6:8])+" "+match[3].(string)
				homeId:=strconv.FormatFloat(match[4].(float64), 'f', -1, 64)
				homeName:=match[5].(string)
				awayId:=strconv.FormatFloat(match[8].(float64), 'f', -1, 64)
				awayName:=match[9].(string)
				scoreString:=strings.Replace(match[12].(string)," ","",-1)
				extraTimed:="0"
				if strings.Contains(scoreString,"*"){
					scoreString=strings.Replace(scoreString,"*","",-1)
					extraTimed="1"
				}

				score:=strings.Split(scoreString,":")
				if len(score)<2{
					return nil
				}
				homeScore:=score[0]
				awayScore:=score[1]
				detailed:="0"
				if strings.Contains(s,region){
					detailed="1"
				}
				if i==999{
					sql+="("+matchId+",'"+regionName+"','"+regionCode+"','"+tournamentName+"','"+stageId+"','"+
						season+"','"+homeId+"','"+ awayId+"','"+homeName+"','"+
						awayName+"','"+homeScore+"','"+awayScore+"','"+detailed+"','"+
						extraTimed+"','"+timeString+"')"

					mysql.Insert(sql)
					sql="insert into `match` values "
					fmt.Println(i)
					i=0
				}else{
					sql+="("+matchId+",'"+regionName+"','"+regionCode+"','"+tournamentName+"','"+stageId+"','"+
						season+"','"+homeId+"','"+ awayId+"','"+homeName+"','"+
						awayName+"','"+homeScore+"','"+awayScore+"','"+detailed+"','"+
						extraTimed+"','"+timeString+"'),"

				}

				i++

				return nil
			})
			return nil
		})
	})
	sql=strings.TrimRight(sql,",")

	mysql.Insert(sql)
	fmt.Println(i)
}
